import { FormEventHandler, HTMLAttributes, RefObject, useEffect } from "react"
import styled from "@emotion/styled"
import {
    useForm,
    FormProvider,
    Control,
    UseFormHandleSubmit,
    FieldValues,
    FormState,
} from "react-hook-form"
import InputPassword from "@/components/form_item/InputPassword"
import InputText from "@/components/form_item/InputText"
import InputEmail from "@/components/form_item/InputEmail"
import InputPhoneNumber from "@/components/form_item/InputPhoneNumber"
import CodeCountdownTimer from "@/components/form_item/CodeCountdownTimer"
import InputCode from "@/components/form_item/InputCode"
import ButtonRegular from "@/components/composite/ButtonRegular/main"
import { DataPickerType } from "@/components/form_item/formItemConfig"

type Props = HTMLAttributes<HTMLDivElement> & {
    ref?: RefObject<unknown>
    queryList: (queryKeyType | DataPickerType)[]
    onSubmit: FormEventHandler<HTMLDivElement> &
        (() => Promise<void>) &
        _.DebouncedFuncLeading<(data: never) => Promise<void>>
    sendCode?: () => Promise<{ success: boolean }>
    back?: () => void
    showSubmitButton?: boolean
    excludingUIName?: object
    buttonText?: string
}

type queryKeyType =
    | "username"
    | "submitButton"
    | "phone"
    | "verify"
    | "code"
    | "cutdown"
    | "emailNoPlaceholder"
    | "password"
    | "passwordNoPlaceholder"
    | "phoneNoPlaceholder"

const FormFieldItem = (props: {
    key: queryKeyType | DataPickerType
    control: Control
    reset: Props
    formState: FormState<FieldValues>
    handleSubmit: UseFormHandleSubmit<FieldValues>
    buttonText?: string
}) => {
    const { key, control, reset, handleSubmit, formState, buttonText } = props
    switch (key) {
        case "username": // queryKeyType === apiKey
            return (
                <InputText
                    key={key}
                    fieldName={"username"}
                    showPlaceholder={true}
                    placeholder={"User Name(5-30)"}
                />
            )
        case "emailNoPlaceholder":
            return (
                <InputEmail
                    key={key}
                    fieldName={"email"}
                    showPlaceholder={false}
                />
            )
        case "code": //邮箱验证码。短信验证码
            return (
                <InputCode
                    key={key}
                    fieldName={"code"}
                    control={control}
                    callBackSubmit={reset?.onSubmit}
                    ref={reset?.ref}
                />
            )
        case "cutdown":
            return (
                <CodeCountdownTimer
                    key={key}
                    // @ts-ignore
                    sendCode={reset?.sendCode}
                ></CodeCountdownTimer>
            )
        case "verify":
            return (
                <>
                    <InputCode
                        key={key}
                        fieldName={"code"}
                        control={control}
                        callBackSubmit={reset?.onSubmit}
                        ref={reset?.ref}
                    />
                    <GapBox>
                        <CodeCountdownTimer
                            style={{ marginTop: "12rem" }}
                            key={key}
                            // @ts-ignore
                            sendCode={reset?.sendCode}
                        />
                    </GapBox>
                </>
            )
        case "phoneNoPlaceholder":
            return (
                <InputPhoneNumber
                    key={key}
                    fieldName={"phone"}
                    showPlaceholder={false}
                />
            )
        case "phone":
            return (
                <InputPhoneNumber
                    key={key}
                    fieldName={"phone"}
                    showPlaceholder={true}
                    placeholder={"Phone Number"}
                />
            )
        case "passwordNoPlaceholder":
            return (
                <InputPassword
                    key={key}
                    fieldName={"password"}
                    showPlaceholder={false}
                />
            )
        case "password":
            return (
                <InputPassword
                    key={key}
                    fieldName={"password"}
                    showVerifyBox={true}
                    showPlaceholder={true}
                    placeholder={"Enter password"}
                />
            )
        case "submitButton":
            return (
                <SubmitButton
                    key={key}
                    onClick={handleSubmit(reset?.onSubmit)}
                    // @ts-ignore
                    variant={
                        formState.isValid
                            ? SubmitButtonVerifyOkBackgroundColor
                            : SubmitButtonBackgroundColor
                    }
                >
                    {buttonText || "Confirm"}
                </SubmitButton>
            )
        //后面还可以继续添加queryKeyType
        default:
            return null
    }
}

function ReactFormProvider(props: Props) {
    const {
        showSubmitButton = false,
        onSubmit,
        excludingUIName,
        queryList,
        ref,
        children,
        buttonText,
    } = props

    const methods = useForm()
    const { control, reset, handleSubmit, formState } = methods
    useEffect(() => {
        if (excludingUIName && Object.keys(excludingUIName as object).length > 0) {
            reset(excludingUIName)
        }
    }, [reset, excludingUIName])
    return (
        <FormProvider {...methods}>
            {queryList?.map((list, idnex) => {
                return FormFieldItem({
                    key: list,
                    control: control,
                    reset: props,
                    formState,
                    handleSubmit,
                    buttonText,
                })
            })}
            {/* {showSubmitButton && (
                <SubmitButton
                    onClick={handleSubmit(onSubmit)}
                    // @ts-ignore
                    variant={
                        formState.isValid
                            ? SubmitButtonVerifyOkBackgroundColor
                            : SubmitButtonBackgroundColor
                    }
                >
                    {buttonText}
                </SubmitButton>
            )} */}
        </FormProvider>
    )
}

export default ReactFormProvider

const SubmitButtonBackgroundColor = {
    type: "solid",
    backgroundColorLeft: "#FF99B3 1.52%",
    backgroundColorRight: "#FFC2EB 100%",
}

const SubmitButtonVerifyOkBackgroundColor = {
    type: "solid",
    backgroundColorLeft: "#FF3568 1.52%",
    backgroundColorRight: "#FF5CC9 100%",
}

const SubmitButton = styled(ButtonRegular)`
    height: 48rem;
    width: 100%;
    font-family: "Gilroy", sans-serif;
    font-weight: 500;
    font-size: 16rem;
    line-height: 24rem;
    letter-spacing: 0;
    text-align: center;
    outline: none;
    border: none;
    box-shadow: none;
    margin-top: 84rem;
`
const Wrapper = styled.div``

const GapBox = styled.div`
    margin-top: 12rem;
`
